//
//  AddressListViewController.m
//  HongFuShop
//
//  Created by chirui on 2017/8/15.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "AddressListViewController.h"
#import "NewAddressViewController.h"
#import "ShopMainViewController.h"
#import "ShopClassViewController.h"
#import "ShopOrderListViewController.h"

@interface AddressListViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>{
    
    UITableView * _tableView;
    NSArray * _dataArray;
    UIView * noBodyView;
    NSString * addressIdStr;
    
}

@end

@implementation AddressListViewController

-(void)viewWillAppear:(BOOL)animated {

    [self getAddressListForNet];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    TitleView(@"收货地址")
    
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithIcon:@"icon_nav_address_add" target:self action:@selector(addBtnClick)];
    
     noBodyView = [NothingMessageView creatNothingMessageViewFrame:CGRectMake(WIDTH/2-100, (HEIGHT-64)/2-150, 200, 200) andMessageStr:@"没有相关内容！" onView:nil];
    
    [self creatTableView];
    [self creatTabbarImageView];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_return_back" target:self action:@selector(backClick)];
    [self getAddressListForNet];
}

-(void)backClick{
    
     [self.navigationController popToRootViewControllerAnimated:YES];
}
-(void)creatTabbarImageView{
    
    NSArray * imageArray = @[@"icon_tab_hot_pre",@"icon_tab_classification_pre",@"icon_tab_order_pre",@"icon_tab_add"];
    NSArray * titleArray = @[@"热卖",@"分类",@"订单",@"收货地址"];
    UIView * view =[[UIView alloc]initWithFrame:CGRectMake(0,HEIGHT-49-SH_TopHeight, WIDTH, 49)];
    view.backgroundColor =[UIColor whiteColor];
    UIView * lineView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 0.5)];
    lineView.backgroundColor =[UIColor groupTableViewBackgroundColor];
    [view addSubview:lineView];
    [self.view addSubview:view];
    for (int j=0; j<4;j++) {
        UIButton * endThreeBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        endThreeBtn.frame = CGRectMake((WIDTH/4)*j, 5, WIDTH/4,32);
        [endThreeBtn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@",imageArray[j]]] forState:UIControlStateNormal];
        [endThreeBtn addTarget:self action:@selector(downBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        endThreeBtn.tag =1000+j;
        
        [view addSubview:endThreeBtn];
        
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake((WIDTH/4)*j,36, WIDTH/4,12)];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = titleArray[j];
        label.font = [UIFont systemFontOfSize:10];
        label.textColor = [UIColor lightGrayColor];
        [view addSubview:label];
        if (j==3) {
            label.textColor = [UIColor orangeColor];
        }
    }
    [self.view addSubview:view];
    
}

-(void)downBtnClick:(UIButton *)btn {
    
    if (btn.tag == 1001) {
        
        ShopClassViewController * shopClass =[[ShopClassViewController alloc]init];
        [self.navigationController pushViewController:shopClass animated:NO];
    }
    if (btn.tag == 1000) {
        
        ShopMainViewController * shoper =[[ShopMainViewController alloc]init];
        [self.navigationController pushViewController:shoper animated:NO];
    }
    if (btn.tag == 1002) {
        
        ShopOrderListViewController * shoper =[[ShopOrderListViewController alloc]init];
        [self.navigationController pushViewController:shoper animated:NO];
    }
    
}


-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)addBtnClick{

    NewAddressViewController * new =[[NewAddressViewController alloc]init];
    [self.navigationController pushViewController:new animated:YES];

}

-(void)creatTableView {
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT -49-SH_TopHeight) style:UITableViewStyleGrouped];
//    if (ISPX) {
//
//        _tableView.frame = CGRectMake(0, 0, WIDTH, HEIGHT-48-34);
//    }
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView = view;
    [self.view addSubview:_tableView];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 130;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * cellId = @"cellId";
    
    UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:cellId ];
    if (cell==nil) {
        
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
    }else {
        while ([cell.contentView.subviews lastObject]!=nil) {
            
              [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary * dic = _dataArray[indexPath.row];
    
    cell.contentView.backgroundColor =[UIColor groupTableViewBackgroundColor];
    UIView * bgView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 120)];
    bgView.backgroundColor = [UIColor whiteColor];

    
    UILabel * nameLabel = [self creatLabelFrame:CGRectMake(10, 10, 120, 20) andTextColor:[UIColor blackColor] andText:dic[@"fullname"] andFont:15 andAliment:NSTextAlignmentLeft onView:bgView];
    
    UILabel *phoneLabel=  [self creatLabelFrame:CGRectMake(140, 10, WIDTH - 150, 20) andTextColor:[UIColor blackColor] andText:dic[@"phone"] andFont:15 andAliment:NSTextAlignmentRight onView:bgView];
    
    UILabel * addressLabel =   [self creatLabelFrame:CGRectMake(10, 40, WIDTH - 40, 20) andTextColor:[UIColor blackColor] andText:[NSString stringWithFormat:@"%@%@%@%@",dic[@"province"],dic[@"city"],dic[@"county"],dic[@"address"]] andFont:15 andAliment:NSTextAlignmentLeft onView:bgView];
    addressLabel.numberOfLines =2;
    [addressLabel sizeToFit];
    
    
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 80, WIDTH, 0.5)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [bgView addSubview:lineView];
    
    UIButton * moreBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    moreBtn.frame = CGRectMake(10, CGRectGetMaxY(lineView.frame)+10, 100, 25);
    [moreBtn setImage:ImageName(@"icon_address_choice_pre") forState:UIControlStateNormal];
    [moreBtn setImage:ImageName(@"icon_address_choice") forState:UIControlStateSelected];
    [moreBtn setTitle:@"设为默认" forState:UIControlStateNormal];
    [moreBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [moreBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    moreBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    moreBtn.tag = 100+indexPath.row;
    [moreBtn addTarget:self action:@selector(moreBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:moreBtn];
    
    if ([dic[@"status"] isEqualToString:@"yes"]) {
        moreBtn.selected = YES;
    }else {
        moreBtn.selected = NO;
    }
    
    
    UIButton * deledateBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    deledateBtn.frame = CGRectMake(WIDTH - 90, CGRectGetMaxY(lineView.frame)+10, 80, 25);
     deledateBtn.tag = 100+indexPath.row;
    [deledateBtn setImage:ImageName(@"icon_nav_address_del") forState:UIControlStateNormal];
    [deledateBtn setTitle:@"删除" forState:UIControlStateNormal];
    [deledateBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    deledateBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [deledateBtn addTarget:self action:@selector(deledateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:deledateBtn];
    
    [cell.contentView addSubview:bgView];
    
    
    
    return cell;
}

-(void)moreBtnClick:(UIButton *)btn{
    
    NSDictionary * dic = _dataArray[btn.tag - 100];

    btn.selected = !btn.selected;
    
    [self setAddressDefaultForAddId:dic[@"id"]];
}

-(void)deledateBtnClick:(UIButton *)btn{

    NSDictionary * dic = _dataArray[btn.tag - 100];
    
    [self deledateAddressForAddId:dic[@"id"]];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary * dic = _dataArray[indexPath.row];
    
     addressIdStr  = dic[@"id"];
   if([self.exChangeGoods isEqualToString:@"choose"]){
        
        
        self.block(dic);
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        
        
    }
}


//地址列表
-(void)getAddressListForNet{
    


    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token")
                           };

    [PostNetWorking postNetWorkingStr:RequestUrlStr(address_list_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;

        if (codeSucess) {

            if ([responseObject[@"datas"][@"lists"] isKindOfClass:[NSArray class]]) {

                _dataArray = responseObject[@"datas"][@"lists"];
            }

            if (_dataArray.count>0) {

                noBodyView.hidden = YES;
            }else {

                noBodyView.hidden = NO;
                [self.view addSubview:noBodyView];
            }

        }else {

            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }

        [_tableView reloadData];
    } failed:^(NSError *error) {

        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误，请检查网络");
    }];
}

//设置默认
-(void)setAddressDefaultForAddId:(NSString *)addid{
    
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"id":addid
                           };
    [PostNetWorking postNetWorkingStr:RequestUrlStr(set_addressMore_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {

            [self getAddressListForNet];
        }else {

            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }

        [_tableView reloadData];
    } failed:^(NSError *error) {

        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误，请检查网络");
    }];

}


//删除地址
-(void)deledateAddressForAddId:(NSString *)addid{


    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"id":addid
                           };
    [PostNetWorking postNetWorkingStr:RequestUrlStr(deledate_address_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            
            [self getAddressListForNet];
        }else {

            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }

        [_tableView reloadData];
    } failed:^(NSError *error) {

        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误，请检查网络");
    }];
    
}


-(UILabel *)creatLabelFrame:(CGRect)rec andTextColor:(UIColor*)col andText:(NSString *)text andFont:(CGFloat)flo andAliment:(NSTextAlignment)aliment onView:(UIView *)view {
    
    
    UILabel * statisLabel =[[UILabel alloc]initWithFrame:rec];
    statisLabel.font = [UIFont systemFontOfSize:flo];
    statisLabel.textColor = col;
    statisLabel.textAlignment = aliment;
    statisLabel.text = text;
    [view addSubview:statisLabel];
    
    return statisLabel;
    
}

@end
